package com.hanhanxiaochong.zhongxiangchuanmei.view.home;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.design.widget.TabLayout;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hanhanxiaochong.zhongxiangchuanmei.R;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.ShopListBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.ShopTypeBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.SymptomBean;
import com.hanhanxiaochong.zhongxiangchuanmei.config.page.PageRecorder;
import com.hanhanxiaochong.zhongxiangchuanmei.presenter.GoodListPresenter;
import com.hanhanxiaochong.zhongxiangchuanmei.util.ResourcesUtils;
import com.hanhanxiaochong.zhongxiangchuanmei.view.base.BaseActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.iview.IGoodListView;
import com.hanhanxiaochong.zhongxiangchuanmei.view.main.adapter.GoodListAdapter;
import com.hanhanxiaochong.zhongxiangchuanmei.view.shop.act.GoodDetailActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.widget.WrapLinearLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.tencent.wxop.stat.common.StatConstants.LOG_TAG;

public class GoodListActivity extends BaseActivity<GoodListPresenter> implements IGoodListView {

    @BindView(R.id.ll_topleft)
    LinearLayout llTopleft;
    @BindView(R.id.tl_tab)
    TabLayout tlTab;
    @BindView(R.id.tv_option_evaluation)
    TextView tvOptionEvaluation;
    @BindView(R.id.tv_option_price)
    TextView tvOptionPrice;
    @BindView(R.id.tv_option_sales)
    TextView tvOptionSales;
    @BindView(R.id.tv_option_filter)
    TextView tvOptionFilter;
    @BindView(R.id.ll_shaixuan)
    LinearLayout llShaixuan;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    @BindView(R.id.good_filter_reset)
    AppCompatTextView goodFilterReset;
    @BindView(R.id.good_filter_sure)
    AppCompatTextView goodFilterSure;
    @BindView(R.id.ll_right_menu)
    LinearLayoutCompat llRightMenu;
    @BindView(R.id.good_list_drawer)
    DrawerLayout goodListDrawer;
    @BindView(R.id.tv_self_support)
    TextView tvSelfSupport;
    @BindView(R.id.tv_joint_venture)
    TextView tvJointVenture;
    @BindView(R.id.et_lowest_price)
    AppCompatEditText etLowestPrice;
    @BindView(R.id.et_highest_price)
    AppCompatEditText etHighestPrice;
    @BindView(R.id.ll_type_container)
    WrapLinearLayout llTypeContainer;
    @BindView(R.id.ll_effect_container)
    WrapLinearLayout llEffectContainer;

    //从首页商城跳转没有店铺id,从门店详情下面的产品列表跳转则有店铺id
    private String store_id;
    //商品名称[默认为空]
    private String name = "";
    //二级分类id
    private String t_id = "";
    //筛选评价0:升序；1：降序
    private String comment = "";
    //筛选价格0:升序；1：降序
    private String price = "";
    //筛选销量0:升序；1：降序
    private String sell_num = "";
    //筛选是否自营(y:查看自营；n：看合盈)
    private String self_sup = "";
    //筛选价格区间最低价
    private String price_s = "";
    //筛选价格区间最高价
    private String price_d = "";
    //筛选三级分类id多选以,隔开
    private String s_id = "";
    private List<String> thirdTypeIdList = new ArrayList<>();
    private StringBuilder sb_thirdType = new StringBuilder();
    //筛选功效id多选以,隔开
    private String symptom = "";
    private List<String> symptomIdList = new ArrayList<>();
    private StringBuilder sb_symptom = new StringBuilder();
    private int present_option;
    private PageRecorder recorder = new PageRecorder();
    private GoodListAdapter goodListAdapter;
    private boolean isFirst = true;
    //第三级分类列表
    private List<ShopTypeBean.ThirdTypeBean> thirdTypeList;
    //适应症状列表
    private List<SymptomBean> symptomList;

    public static Intent createIntent(Context context, String t_id, String store_id) {
        Intent intent = new Intent(context, GoodListActivity.class);
        intent.putExtra("t_id", t_id);
        intent.putExtra("store_id", store_id);
        return intent;
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_good_list);
        t_id = getIntent().getStringExtra("t_id");
        store_id = getIntent().getStringExtra("store_id");
    }

    @Override
    protected void initPresenter() {
        mPresenter = new GoodListPresenter(this);
    }

    @Override
    protected void init() {
        mPresenter.getShopType(t_id);
        getData();
        mPresenter.getSymptoms();
        smartRefresh.setEnableRefresh(false);
        smartRefresh.setOnLoadmoreListener(refreshlayout -> getData());

        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        List<ShopListBean> list = new ArrayList<>();
        goodListAdapter = new GoodListAdapter(this, R.layout.item_shop, list);
        recyclerview.setAdapter(goodListAdapter);
        goodListAdapter.setmOnItemClickListener((adapter, position) ->
                startActivity(GoodDetailActivity.createIntent(this, goodListAdapter.getDatas().get(position).getId(),store_id)));
    }

    @OnClick({R.id.ll_topleft, R.id.tv_option_evaluation, R.id.tv_option_price, R.id.tv_option_sales,
            R.id.ll_shaixuan, R.id.tv_self_support, R.id.tv_joint_venture, R.id.good_filter_reset, R.id.good_filter_sure})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.ll_topleft:
                finish();
                break;
            case R.id.tv_option_evaluation:
                //判断当前筛选项
                if (present_option == 1) {
                    //判断当前排序状态
                    if (comment.equals("0")) {
                        comment = "1";
                        setDrawableRight(tvOptionEvaluation, R.drawable.sort_high_to_low);
                    } else {
                        setDrawableRight(tvOptionEvaluation, R.drawable.sort_low_to_high);
                        comment = "0";
                    }
                } else {
                    comment = "0";
                    present_option = 1;
                    selectSortOption(present_option);
                }
                recorder.moveToFirstPage();
                getData();
                break;
            case R.id.tv_option_price:
                //判断当前筛选项
                if (present_option == 2) {
                    //判断当前排序状态
                    if (price.equals("0")) {
                        price = "1";
                        setDrawableRight(tvOptionPrice, R.drawable.sort_high_to_low);
                    } else {
                        setDrawableRight(tvOptionPrice, R.drawable.sort_low_to_high);
                        price = "0";
                    }
                } else {
                    price = "0";
                    present_option = 2;
                    selectSortOption(present_option);
                }
                recorder.moveToFirstPage();
                getData();
                break;
            case R.id.tv_option_sales:
                //判断当前筛选项
                if (present_option == 3) {
                    //判断当前排序状态
                    if (sell_num.equals("0")) {
                        sell_num = "1";
                        setDrawableRight(tvOptionSales, R.drawable.sort_high_to_low);
                    } else {
                        setDrawableRight(tvOptionSales, R.drawable.sort_low_to_high);
                        sell_num = "0";
                    }
                } else {
                    sell_num = "0";
                    present_option = 3;
                    selectSortOption(present_option);
                }
                recorder.moveToFirstPage();
                getData();
                break;
            case R.id.ll_shaixuan:
                if (!goodListDrawer.isDrawerOpen(Gravity.END)) {
                    goodListDrawer.openDrawer(Gravity.END);
                }
                break;
            case R.id.tv_self_support:
                tvJointVenture.setSelected(false);
                tvSelfSupport.setSelected(!tvSelfSupport.isSelected());
                self_sup = tvSelfSupport.isSelected() ? "y" : "";
                break;
            case R.id.tv_joint_venture:
                tvSelfSupport.setSelected(false);
                tvJointVenture.setSelected(!tvJointVenture.isSelected());
                self_sup = tvJointVenture.isSelected() ? "n" : "";
                break;
            //重置
            case R.id.good_filter_reset:
                tvJointVenture.setSelected(false);
                tvSelfSupport.setSelected(false);
                self_sup = "";
                price_d = "";
                price_s = "";
                etLowestPrice.setText("");
                etHighestPrice.setText("");
                setThirdTypeList(thirdTypeList);
                setSymptoms(symptomList);
                break;
            //确定
            case R.id.good_filter_sure:
                sb_thirdType.reverse();
                sb_symptom.reverse();
                for (int i = 0; i < thirdTypeIdList.size(); i++) {
                    sb_thirdType.append(i != thirdTypeIdList.size() - 1 ? thirdTypeIdList.get(i) + "," : thirdTypeIdList.get(i));
                }
                s_id = sb_thirdType.toString();
                for (int i = 0; i < symptomIdList.size(); i++) {
                    sb_symptom.append(i != symptomIdList.size() - 1 ? symptomIdList.get(i) + "," : symptomIdList.get(i));
                }
                symptom = sb_symptom.toString();
                price_s = etLowestPrice.getText().toString().trim();
                price_d = etHighestPrice.getText().toString().trim();
                getData();
                goodListDrawer.closeDrawers();
                break;
        }
    }

    /**
     * 根据当前排序类型切换图标
     *
     * @param index 1综合,2销量,3价格
     */
    private void selectSortOption(int index) {
        switch (index) {
            case 1:
                tvOptionEvaluation.setSelected(true);
                tvOptionPrice.setSelected(false);
                tvOptionSales.setSelected(false);
                setDrawableRight(tvOptionEvaluation, R.drawable.sort_low_to_high);
                setDrawableRight(tvOptionPrice, R.drawable.sort_default);
                setDrawableRight(tvOptionSales, R.drawable.sort_default);
                break;
            case 2:
                tvOptionEvaluation.setSelected(false);
                tvOptionPrice.setSelected(true);
                tvOptionSales.setSelected(false);
                setDrawableRight(tvOptionEvaluation, R.drawable.sort_default);
                setDrawableRight(tvOptionPrice, R.drawable.sort_low_to_high);
                setDrawableRight(tvOptionSales, R.drawable.sort_default);
                break;
            case 3:
                tvOptionEvaluation.setSelected(false);
                tvOptionPrice.setSelected(false);
                tvOptionSales.setSelected(true);
                setDrawableRight(tvOptionEvaluation, R.drawable.sort_default);
                setDrawableRight(tvOptionPrice, R.drawable.sort_default);
                setDrawableRight(tvOptionSales, R.drawable.sort_low_to_high);
                break;
            default:
                tvOptionEvaluation.setSelected(false);
                tvOptionPrice.setSelected(false);
                tvOptionSales.setSelected(false);
                setDrawableRight(tvOptionEvaluation, R.drawable.sort_default);
                setDrawableRight(tvOptionPrice, R.drawable.sort_default);
                setDrawableRight(tvOptionSales, R.drawable.sort_default);
                break;
        }
    }

    private void setDrawableRight(TextView textView, int resource) {
        Drawable drawable = getResources().getDrawable(resource);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        textView.setCompoundDrawables(null, null, drawable, null);
    }

    @Override
    public void setData(List<ShopListBean> data) {
        goodListAdapter.setDatas(data);
        recorder.moveToNextPage();
    }

    @Override
    public void addData(List<ShopListBean> data) {
        goodListAdapter.addDatas(data);
        recorder.moveToNextPage();
    }

    @Override
    public void setShopType(List<ShopTypeBean.ThirdTypeBean> type) {
        thirdTypeList = type;
        setThirdTypeList(thirdTypeList);
        ShopTypeBean.ThirdTypeBean typeBean = new ShopTypeBean.ThirdTypeBean();
        typeBean.setName("热门推荐");
        typeBean.setId("");
        type.add(0, typeBean);
        tlTab.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                try {
                    if (tab.getPosition() != 0) {
                        llShaixuan.setVisibility(View.VISIBLE);
                        s_id = type.get(tab.getPosition()).getId();
                        getData();
                    } else {
                        llShaixuan.setVisibility(View.GONE);
                        s_id = "";
                        getData();
                    }
                } catch (IndexOutOfBoundsException exception) {
                    Log.i(LOG_TAG, "onTabSelected: " + exception.toString());
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

        //添加tab
        for (int i = 0; i < type.size(); i++) {
            tlTab.addTab(tlTab.newTab().setText(type.get(i).getName()));
        }
        isFirst = false;
    }

    private void setThirdTypeList(List<ShopTypeBean.ThirdTypeBean> type) {
        llTypeContainer.removeAllViews();
        for (ShopTypeBean.ThirdTypeBean bean : type) {
            //添加右侧筛选项
            View view = ResourcesUtils.inflate(R.layout.item_filter_option);
            TextView textView = view.findViewById(R.id.tv_item_option);
            textView.setText(bean.getName());
            view.setOnClickListener(v -> {
                textView.setSelected(!textView.isSelected());
                if (textView.isSelected()) {
                    thirdTypeIdList.add(bean.getId());
                } else {
                    thirdTypeIdList.remove(bean.getId());
                }
            });
            llTypeContainer.addView(view);
        }
    }

    @Override
    public void setSymptoms(List<SymptomBean> data) {
        symptomList = data;
        llEffectContainer.removeAllViews();
        for (SymptomBean bean : data) {
            View view = ResourcesUtils.inflate(R.layout.item_filter_option);
            TextView textView = view.findViewById(R.id.tv_item_option);
            textView.setText(bean.getName());
            view.setOnClickListener(v -> {
                textView.setSelected(!textView.isSelected());
                if (textView.isSelected()) {
                    symptomIdList.add(bean.getId());
                } else {
                    symptomIdList.remove(bean.getId());
                }
            });
            llEffectContainer.addView(view);
        }
    }

    private void getData() {
        mPresenter.getList(name, t_id, comment, price, sell_num, self_sup, price_s, price_d, s_id, symptom, String.valueOf(recorder.getCurrentPage()));
    }
}
